#coding=utf-8
from stutils import *
set_django_environ()
from stdj.stock.models import *
from stindex.indexdb import get_exdayslist
import datetime
td = datetime.date.today().isoformat()
def is_hengpan(e, n=10, t=[7, 14]):
    '''判断从今天以前n交易日到今天(包括今天),该股票是否处于横盘整理状态.'''
    ps = e.prenday_ps(n)
    if not ps:return False
    
    ps.insert(0, e.price)
    
    #指标1
    end = ps[0].end
    start = ps[-1].end
    change = float( (end-start)*100/end ) 
    change = abs(change)
    
    #指标2
    h = max( [p.high for p in ps] )
    l = min( [p.low for p in ps] )
    avg = sum( [p.end for p in ps] )/ len(ps)
    
    f = float( (h-l)*100/avg )
    
    #print change, f
    x,y = t
    if change < x and f < y:
        return True
    return False
       
def get_hp(con, exdate, n=20):
    name = 'hp%i'%n
    c = con.cursor()
    c.execute('select code from selected where date=? and strategy=?', (exdate,name))
    r = c.fetchall()
    
    if not r:return None
    return [i[0] for i in r]

if __name__ == '__main__':
    from strategy import *
    con = get_con()    
    name = 'hp20' 
    eds = [td,]
    for ed in eds:
        print ed
        for s in Share.objects.order_by('code'):
            try:
                e = s.exday_set.get(date = ed)
            except Exday.DoesNotExist, ex:
                continue
        
            if is_hengpan(e, 20):
                selected2db(con, e, name)